from rest_framework.generics import CreateAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from course.models import Course
from django_redis import get_redis_connection

from django.conf import settings
from . import models, serializer
from users.models import User
# Create your views here.


class OrderListView(ViewSet):
	permission_classes = [IsAuthenticated, ]

	def orderList(self, request):
		user_id = request.user.id
		conn = get_redis_connection('cart')
		carts = conn.hgetall(f'cart_{user_id}')
		select_course = conn.smembers(f'selected_{user_id}')
		data = []
		if select_course and carts:
			try:
				for course_id_byte in select_course:
					if course_id_byte in carts:
						try:
							course = Course.objects.get(is_show=True, is_deleted=False, id=int(course_id_byte.decode()))
							expire_time = course.get_expire(carts.get(course_id_byte).decode())
						except:
							return Response({'error': '该课程不存在'}, status=400)
						data.append({
							'name': course.name,
							'id': course.id,
							'expire': expire_time,
							'real_price': course.real_price(int(carts.get(course_id_byte).decode())),
							'course_img': course.course_img.url.replace('/media', f'{settings.SERVER_HOST}/media'),
						})
				return Response(data)
			except:
				return Response({'error': '未勾选商品'}, status=400)
		return Response({'error': '购物车中没有商品'}, status=400)


class OrderCreateView(CreateAPIView):
	permission_classes = [IsAuthenticated, ]
	queryset = models.Order.objects.filter(is_show=True, is_deleted=False)
	serializer_class = serializer.OrderModelSerializer


class MyOrderView(RetrieveAPIView):
	permission_classes = [IsAuthenticated, ]
	serializer_class = serializer.UserOrderModelSerializer
	queryset = User.objects.all()
